const LearningPath = require('../models/LearningPath');
const UserLearningProgress = require('../models/UserLearningProgress');
const Document = require('../models/Document');
const Card = require('../models/Card');
const Exercise = require('../models/Exercise');

/**
 * @desc    自动生成学习路径
 * @route   POST /api/learning-paths/generate/:documentId
 * @access  私有
 */
const generateLearningPath = async (req, res) => {
  try {
    const { documentId } = req.params;
    console.log(`[generateLearningPath] 开始为文档 ${documentId} 生成学习路径`);
    
    // 检查文档是否存在
    const document = await Document.findById(documentId);
    if (!document) {
      console.log(`[generateLearningPath] 文档 ${documentId} 不存在`);
      return res.status(404).json({ message: '文档不存在' });
    }
    
    // 检查文档是否已处理完成
    if (!document.processed) {
      console.log(`[generateLearningPath] 文档 ${documentId} 尚未处理完成`);
      return res.status(400).json({ message: '文档尚未处理完成，无法生成学习路径' });
    }
    
    // 获取文档相关的所有卡片，按章节和序号排序
    const cards = await Card.find({ sourceDocument: documentId }).sort({ chapter: 1, order: 1 });
    console.log(`[generateLearningPath] 找到文档相关的卡片: ${cards.length} 张`);
    
    if (cards.length === 0) {
      console.log(`[generateLearningPath] 文档 ${documentId} 没有关联的知识卡片`);
      return res.status(400).json({ message: '文档没有关联的知识卡片，无法生成学习路径' });
    }
    
    // 获取文档相关的所有练习题
    const exercises = await Exercise.find({ sourceDocument: documentId }).sort({ difficulty: 1 });
    console.log(`[generateLearningPath] 找到文档相关的练习题: ${exercises.length} 道`);
    
    // 按章节分组卡片
    const cardsByChapter = {};
    cards.forEach(card => {
      if (!cardsByChapter[card.chapter]) {
        cardsByChapter[card.chapter] = [];
      }
      cardsByChapter[card.chapter].push(card);
    });
    
    console.log(`[generateLearningPath] 卡片按章节分组: ${Object.keys(cardsByChapter).length} 个章节`);
    
    // 创建学习路径
    const learningPath = new LearningPath({
      title: `${document.title} 学习路径`,
      description: `系统自动生成的 ${document.title} 学习路径，包含 ${cards.length} 张知识卡片和 ${exercises.length} 道练习题。`,
      documentId,
      createdBy: req.user._id,
      isAutoGenerated: true,
      stages: []
    });
    
    // 为每个章节创建学习阶段
    let stageOrder = 1;
    for (const chapter in cardsByChapter) {
      const chapterCards = cardsByChapter[chapter];
      console.log(`[generateLearningPath] 为第 ${chapter} 章创建学习阶段，包含 ${chapterCards.length} 张卡片`);
      
      // 创建阶段
      const stage = {
        title: `第 ${chapter} 章`,
        description: `学习第 ${chapter} 章的知识点，共 ${chapterCards.length} 张卡片`,
        order: stageOrder++,
        steps: []
      };
      
      // 为每张卡片创建学习步骤
      let stepOrder = 1;
      chapterCards.forEach(card => {
        // 添加卡片学习步骤
        stage.steps.push({
          title: `学习: ${card.title}`,
          description: `学习卡片内容并理解知识点`,
          cardId: card._id,
          order: stepOrder++,
          estimatedTime: 5 // 预计5分钟学习一张卡片
        });
        
        // 查找与该卡片相关的练习题
        const cardExercises = exercises.filter(e => e.cardId && e.cardId.toString() === card._id.toString());
        if (cardExercises.length > 0) {
          console.log(`[generateLearningPath] 为卡片 ${card._id} 添加 ${Math.min(cardExercises.length, 3)} 道练习题`);
          // 每张卡片最多添加3道练习题
          const limitedExercises = cardExercises.slice(0, 3);
          limitedExercises.forEach(exercise => {
            stage.steps.push({
              title: `练习: ${exercise.question.substring(0, 30)}...`,
              description: `完成与 ${card.title} 相关的练习题`,
              exerciseId: exercise._id,
              order: stepOrder++,
              estimatedTime: 3 // 预计3分钟完成一道练习题
            });
          });
        }
      });
      
      // 将阶段添加到学习路径
      learningPath.stages.push(stage);
    }
    
    console.log(`[generateLearningPath] 学习路径创建完成，包含 ${learningPath.stages.length} 个阶段`);
    
    // 保存学习路径
    await learningPath.save();
    console.log(`[generateLearningPath] 学习路径已保存，ID: ${learningPath._id}`);
    
    res.status(201).json({
      message: '学习路径生成成功',
      learningPath: {
        _id: learningPath._id,
        title: learningPath.title,
        description: learningPath.description,
        stagesCount: learningPath.stages.length,
        totalSteps: learningPath.stages.reduce((total, stage) => total + stage.steps.length, 0)
      }
    });
  } catch (error) {
    console.error('生成学习路径时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    获取文档的学习路径
 * @route   GET /api/learning-paths/document/:documentId
 * @access  私有
 */
const getLearningPathByDocument = async (req, res) => {
  try {
    const { documentId } = req.params;
    
    // 查找文档的学习路径
    const learningPath = await LearningPath.findOne({ documentId })
      .populate('documentId', 'title');
    
    if (!learningPath) {
      return res.status(404).json({ message: '未找到学习路径' });
    }
    
    // 查找用户的学习进度
    let userProgress = await UserLearningProgress.findOne({
      userId: req.user._id,
      learningPathId: learningPath._id
    });
    
    // 如果用户没有进度记录，创建一个新的
    if (!userProgress) {
      userProgress = new UserLearningProgress({
        userId: req.user._id,
        learningPathId: learningPath._id,
        status: 'not_started',
        stagesProgress: learningPath.stages.map(stage => ({
          stageId: stage._id,
          status: 'not_started',
          stepsProgress: stage.steps.map(step => ({
            stepId: step._id,
            status: 'not_started'
          }))
        }))
      });
      await userProgress.save();
    }
    
    res.json({
      learningPath,
      userProgress
    });
  } catch (error) {
    console.error('获取学习路径时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    获取用户的所有学习路径
 * @route   GET /api/learning-paths/user
 * @access  私有
 */
const getUserLearningPaths = async (req, res) => {
  try {
    console.log(`[getUserLearningPaths] 获取用户 ${req.user._id} 的学习路径`);
    
    // 获取用户的所有学习进度
    const userProgresses = await UserLearningProgress.find({ userId: req.user._id })
      .populate({
        path: 'learningPathId',
        select: 'title description documentId createdAt',
        populate: {
          path: 'documentId',
          select: 'title'
        }
      });
    
    console.log(`[getUserLearningPaths] 找到用户学习进度记录: ${userProgresses.length} 条`);
    
    // 如果用户没有学习进度记录，查找所有学习路径
    if (userProgresses.length === 0) {
      console.log(`[getUserLearningPaths] 用户没有学习进度记录，查找所有学习路径`);
      
      const learningPaths = await LearningPath.find()
        .populate('documentId', 'title')
        .select('title description documentId createdAt');
      
      console.log(`[getUserLearningPaths] 找到学习路径: ${learningPaths.length} 条`);
      
      const formattedPaths = learningPaths.map(path => ({
        _id: path._id,
        title: path.title,
        description: path.description,
        documentTitle: path.documentId ? path.documentId.title : '未知文档',
        documentId: path.documentId,
        createdAt: path.createdAt,
        progress: 0,
        status: 'not_started'
      }));
      
      console.log(`[getUserLearningPaths] 返回格式化学习路径: ${formattedPaths.length} 条`);
      return res.json({
        learningPaths: formattedPaths
      });
    }
    
    // 格式化返回数据
    const formattedPaths = userProgresses.map(progress => ({
      _id: progress.learningPathId._id,
      title: progress.learningPathId.title,
      description: progress.learningPathId.description,
      documentTitle: progress.learningPathId.documentId ? progress.learningPathId.documentId.title : '未知文档',
      documentId: progress.learningPathId.documentId,
      createdAt: progress.learningPathId.createdAt,
      progress: progress.progress,
      status: progress.status,
      lastAccessedAt: progress.lastAccessedAt,
      currentStageIndex: progress.currentStageIndex,
      currentStepIndex: progress.currentStepIndex
    }));
    
    console.log(`[getUserLearningPaths] 返回用户学习路径: ${formattedPaths.length} 条`);
    res.json({ learningPaths: formattedPaths });
  } catch (error) {
    console.error('获取用户学习路径时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    获取学习路径详情
 * @route   GET /api/learning-paths/:id
 * @access  私有
 */
const getLearningPathById = async (req, res) => {
  try {
    const learningPath = await LearningPath.findById(req.params.id)
      .populate('documentId', 'title')
      .populate({
        path: 'stages.steps.cardId',
        select: 'title content difficulty'
      })
      .populate({
        path: 'stages.steps.exerciseId',
        select: 'question type options difficulty'
      });
    
    if (!learningPath) {
      return res.status(404).json({ message: '未找到学习路径' });
    }
    
    // 查找用户的学习进度
    let userProgress = await UserLearningProgress.findOne({
      userId: req.user._id,
      learningPathId: learningPath._id
    });
    
    // 如果用户没有进度记录，创建一个新的
    if (!userProgress) {
      userProgress = new UserLearningProgress({
        userId: req.user._id,
        learningPathId: learningPath._id,
        status: 'not_started',
        stagesProgress: learningPath.stages.map(stage => ({
          stageId: stage._id,
          status: 'not_started',
          stepsProgress: stage.steps.map(step => ({
            stepId: step._id,
            status: 'not_started'
          }))
        }))
      });
      await userProgress.save();
    }
    
    res.json({
      learningPath,
      userProgress
    });
  } catch (error) {
    console.error('获取学习路径详情时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    更新学习步骤状态
 * @route   PUT /api/learning-paths/:id/progress
 * @access  私有
 */
const updateStepProgress = async (req, res) => {
  try {
    const { id } = req.params;
    const { stageIndex, stepIndex, status, timeSpent } = req.body;
    
    // 查找学习路径
    const learningPath = await LearningPath.findById(id);
    if (!learningPath) {
      return res.status(404).json({ message: '未找到学习路径' });
    }
    
    // 验证索引是否有效
    if (stageIndex < 0 || stageIndex >= learningPath.stages.length) {
      return res.status(400).json({ message: '无效的阶段索引' });
    }
    
    if (stepIndex < 0 || stepIndex >= learningPath.stages[stageIndex].steps.length) {
      return res.status(400).json({ message: '无效的步骤索引' });
    }
    
    // 查找或创建用户进度
    let userProgress = await UserLearningProgress.findOne({
      userId: req.user._id,
      learningPathId: id
    });
    
    if (!userProgress) {
      userProgress = new UserLearningProgress({
        userId: req.user._id,
        learningPathId: id,
        status: 'in_progress',
        startedAt: new Date(),
        stagesProgress: []
      });
      
      // 初始化所有阶段和步骤的进度
      for (let i = 0; i < learningPath.stages.length; i++) {
        const stage = learningPath.stages[i];
        const stageProgress = {
          stageId: stage._id,
          status: i === 0 ? 'in_progress' : 'not_started',
          startedAt: i === 0 ? new Date() : undefined,
          stepsProgress: []
        };
        
        for (let j = 0; j < stage.steps.length; j++) {
          const step = stage.steps[j];
          stageProgress.stepsProgress.push({
            stepId: step._id,
            status: (i === 0 && j === 0) ? 'in_progress' : 'not_started',
            startedAt: (i === 0 && j === 0) ? new Date() : undefined
          });
        }
        
        userProgress.stagesProgress.push(stageProgress);
      }
    }
    
    // 更新步骤状态
    const stageProgress = userProgress.stagesProgress[stageIndex];
    const stepProgress = stageProgress.stepsProgress[stepIndex];
    
    // 如果步骤状态从未开始变为进行中，设置开始时间
    if (stepProgress.status === 'not_started' && status === 'in_progress') {
      stepProgress.startedAt = new Date();
    }
    
    // 如果步骤状态变为已完成，设置完成时间
    if (status === 'completed' && stepProgress.status !== 'completed') {
      stepProgress.completedAt = new Date();
      
      // 更新花费时间
      if (timeSpent) {
        stepProgress.timeSpent = timeSpent;
      } else if (stepProgress.startedAt) {
        // 如果没有提供花费时间，计算从开始到现在的时间（分钟）
        const timeDiff = new Date() - stepProgress.startedAt;
        stepProgress.timeSpent = Math.round(timeDiff / 60000); // 毫秒转分钟
      }
      
      // 检查是否所有步骤都已完成，如果是，更新阶段状态
      const allStepsCompleted = stageProgress.stepsProgress.every(step => step.status === 'completed');
      if (allStepsCompleted) {
        stageProgress.status = 'completed';
        stageProgress.completedAt = new Date();
        
        // 检查是否有下一个阶段，如果有，将其状态设为进行中
        if (stageIndex + 1 < userProgress.stagesProgress.length) {
          userProgress.stagesProgress[stageIndex + 1].status = 'in_progress';
          userProgress.stagesProgress[stageIndex + 1].startedAt = new Date();
          userProgress.stagesProgress[stageIndex + 1].stepsProgress[0].status = 'in_progress';
          userProgress.stagesProgress[stageIndex + 1].stepsProgress[0].startedAt = new Date();
          
          // 更新当前阶段和步骤索引
          userProgress.currentStageIndex = stageIndex + 1;
          userProgress.currentStepIndex = 0;
        } else {
          // 如果所有阶段都已完成，更新整个学习路径状态
          userProgress.status = 'completed';
          userProgress.completedAt = new Date();
        }
      } else {
        // 如果还有未完成的步骤，找到下一个未完成的步骤
        const nextStepIndex = stageProgress.stepsProgress.findIndex(step => step.status !== 'completed');
        if (nextStepIndex !== -1) {
          stageProgress.stepsProgress[nextStepIndex].status = 'in_progress';
          stageProgress.stepsProgress[nextStepIndex].startedAt = new Date();
          
          // 更新当前步骤索引
          userProgress.currentStepIndex = nextStepIndex;
        }
      }
    }
    
    // 更新步骤状态
    stepProgress.status = status;
    
    // 计算总体进度百分比
    const totalSteps = userProgress.stagesProgress.reduce((total, stage) => total + stage.stepsProgress.length, 0);
    const completedSteps = userProgress.stagesProgress.reduce((total, stage) => {
      return total + stage.stepsProgress.filter(step => step.status === 'completed').length;
    }, 0);
    
    userProgress.progress = Math.round((completedSteps / totalSteps) * 100);
    
    // 更新最后访问时间
    userProgress.lastAccessedAt = new Date();
    
    // 保存更新
    await userProgress.save();
    
    res.json({
      message: '学习进度更新成功',
      userProgress
    });
  } catch (error) {
    console.error('更新学习进度时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    获取下一个学习步骤
 * @route   GET /api/learning-paths/:id/next-step
 * @access  私有
 */
const getNextStep = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 查找用户的学习进度
    const userProgress = await UserLearningProgress.findOne({
      userId: req.user._id,
      learningPathId: id
    }).populate({
      path: 'learningPathId',
      populate: [
        {
          path: 'stages.steps.cardId',
          select: 'title content difficulty'
        },
        {
          path: 'stages.steps.exerciseId',
          select: 'question type options difficulty'
        }
      ]
    });
    
    if (!userProgress) {
      return res.status(404).json({ message: '未找到学习进度' });
    }
    
    // 如果学习已完成
    if (userProgress.status === 'completed') {
      return res.json({
        completed: true,
        message: '恭喜！您已完成整个学习路径。'
      });
    }
    
    // 获取当前阶段和步骤
    const stageIndex = userProgress.currentStageIndex;
    const stepIndex = userProgress.currentStepIndex;
    
    // 获取学习路径
    const learningPath = userProgress.learningPathId;
    
    // 获取当前阶段和步骤
    const currentStage = learningPath.stages[stageIndex];
    const currentStep = currentStage.steps[stepIndex];
    
    // 返回下一个要学习的步骤
    res.json({
      completed: false,
      currentStage: {
        title: currentStage.title,
        description: currentStage.description,
        order: currentStage.order,
        progress: userProgress.stagesProgress[stageIndex].status
      },
      currentStep: {
        title: currentStep.title,
        description: currentStep.description,
        order: currentStep.order,
        type: currentStep.cardId ? 'card' : 'exercise',
        content: currentStep.cardId ? currentStep.cardId : currentStep.exerciseId,
        progress: userProgress.stagesProgress[stageIndex].stepsProgress[stepIndex].status
      },
      progress: {
        overall: userProgress.progress,
        stageIndex,
        stepIndex,
        totalStages: learningPath.stages.length,
        totalStepsInStage: currentStage.steps.length
      }
    });
  } catch (error) {
    console.error('获取下一个学习步骤时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

module.exports = {
  generateLearningPath,
  getLearningPathByDocument,
  getUserLearningPaths,
  getLearningPathById,
  updateStepProgress,
  getNextStep
}; 